import { login, showToast } from "../../utils/asyncWx.js";
import { request } from "../../request/index.js";

Page({
    data: {
        userInfo: {}
    },
    onShow() {
        var timestamp = Date.parse(new Date()); // 获取当前时间戳,毫秒
        var expiration = wx.getStorageSync("expiration");
        if (!expiration) {
            const userInfo = wx.getStorageSync("userInfo");
            this.setData({
                userInfo: userInfo
            })
        } else {
            // 过期
            if (timestamp > expiration) {
                showToast({ title: "登录失效，请重新登录", icon: "none" });
                wx.removeStorageSync("userInfo");
                wx.removeStorageSync("cart");
                wx.removeStorageSync("address");
                wx.removeStorageSync("expiration");
                this.setData({
                    userInfo: []
                });
                return;
            } else {
                // 未过期更新时间
                wx.setStorageSync("expiration", expiration + 1000 * 60 * 60 * 24 * 3);
                const userInfo = wx.getStorageSync("userInfo");
                this.setData({
                    userInfo: userInfo
                })
            }
        }
    },

    // 获取用户信息
    async handleGetUserInfo(e) {
        wx.showLoading({
            title: '请等候'
        })
        try {
            // 1 获取小程序登录成功后的code及用户相关信息
            const { code } = await login();
            const { userInfo } = e.detail;
            // const loginParams = {
            //     encryptedData,
            //     rawData,
            //     iv,
            //     signature,
            //     code
            // };
            // 2 发送请求 获取用户信息
            const id = await request({ url: "/user/getwUser", data: code, method: "POST" });
            const open_id = id.data.openid;
            const index = await request({ url: "/user/getByOpenId", data: { open_id: open_id }, method: "GET" });

            // 用户已存在
            if (index.data.data.length === 1) {
                // 判断用户状态
                if (index.data.data[0].state === 1) {
                    showToast({ title: "您已被封禁，详情请联系客服", icon: "none" });
                    wx.removeStorageSync("userInfo");
                    wx.removeStorageSync("cart");
                    wx.removeStorageSync("address");
                    wx.removeStorageSync("expiration");
                    this.setData({
                        userInfo: []
                    });
                    return;
                }{
                    const { phone_number, state, email } = index.data.data[0];
                    const Info = {
                        userInfo,
                        phone_number,
                        state,
                        email,
                        open_id
                    }
                    this.setData({
                        userInfo: Info,
                    });
                }
            }
            // 用户不存在
            else {
                // 处理用户信息
                const Info = {
                    userInfo,
                    open_id
                };
                this.setData({
                    userInfo: Info,
                });
                const modifyParams = {
                    openId: open_id,
                    name: this.data.userInfo.userInfo.nickName,
                    email: "",
                    phone_number: ""
                }
                request({ url: "/user/modifyWUser", data: modifyParams, method: "POST" });
            }
            // const { token } = await request({ url: "/users/wxlogin", data: loginParams, method: "POST" });
            // const token = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIzLCJpYXQiOjE1NjQ3MzAwNzksImV4cCI6MTAwMTU2NDczMDA3OH0.YPt-XeLnjV-_1ITaXGY2FhxmCe4NvXuRnRB8OMCfnPo";
            // 4 把userInfo、token存入缓存中 同时跳转回上一个页面
            // 获取当前时间戳,毫秒
            var timestamp = Date.parse(new Date());
            // 设置过期时间3天
            var expiration = timestamp + 1000 * 60 * 60 * 24 * 3;
            wx.setStorageSync("userInfo", this.data.userInfo);
            wx.setStorageSync("expiration", expiration);
            // wx.setStorageSync("token", token);
            wx.hideLoading();
        } catch (err) {
            console.error(err);
            wx.hideLoading();
        }
    },

    async handleOrder(e) {
        const { type } = e.currentTarget.dataset;
        const index = await request({ url: "/user/getByOpenId", data: { open_id: this.data.userInfo.open_id }, method: "GET" });
        // 1 判断登录状态
        if (!this.data.userInfo || this.data.userInfo.length === 0) {
            showToast({ title: "请登录", icon: "none" })
            return;
        } else if (index.data.data.length === 1) {
            // 2 判断用户状态 
            if (index.data.data[0].state === 1) {
                showToast({ title: "您已被封禁，详情请联系客服", icon: "none" });
                wx.removeStorageSync("userInfo");
                wx.removeStorageSync("cart");
                wx.removeStorageSync("address");
                this.setData({
                    userInfo: []
                });
                return;
            }
            wx.navigateTo({
                url: '/pages/order/index?type=' + type,
                success: (res) => {

                },
                fail: () => {
                    showToast({ title: "网络错误", icon: "none" });
                },
                complete: () => {}
            });
        } else {
            showToast({ title: "网络错误", icon: "none" });
        }
    },

    // 退出登录
    handleLogout() {
        showToast({ title: "退出登录成功", icon: "none" });
        wx.removeStorageSync("userInfo");
        wx.removeStorageSync("cart");
        wx.removeStorageSync("address");
        wx.removeStorageSync("expiration");
        this.setData({
            userInfo: []
        })
        this.onShow();
    }
})